package mygui

import (
	//"image/color"
	"fyne.io/fyne/v2"
	//"fyne.io/fyne/v2/app"
	//"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/storage"
	"os"
	"fmt"
	"time"
	//"encoding/csv"
	"encoding/json"
	//"io"
	//"bufio"
	//"errors"
	//"bytes"
	//"github.com/flopp/go-findfont"
	"strings"
	//"reflect"
	//"net/http"
    //"io/ioutil"
    //"net/url"
    //"regexp"
    "strconv"
)

/*
func init() {
    fontPaths := findfont.List()
    for _, path := range fontPaths {
        //fmt.Println(path)
        //楷体:simkai.ttf
        //黑体:simhei.ttf
        if strings.Contains(path, "simkai.ttf") {
            fmt.Println(path)
            os.Setenv("FYNE_FONT", path) // 设置环境变量  // 取消环境变量 os.Unsetenv("FYNE_FONT")
            break
        }
    }
    fmt.Println("=============")
}
*/

var (
	MconfigIP string
)



func Upload_main(myApp fyne.App, t_data chan int) fyne.Window {
	var sadata = []string{"手动上传", "自动下载上传"}
	var ladata = []string{"游戏Fan", "联想", "九游","一元"}
	var vadata = []string{"新增","消费"}
	var Ldata  = [][]string{[]string{"账号","密码"}}
	//myApp := app.New()
	myWindow := myApp.NewWindow("上传界面")

	input := widget.NewEntry()
	input.SetPlaceHolder("游戏名字")
	//input.Hide()

	input1 := widget.NewEntry()
	input1.SetPlaceHolder("数量")
	input1.Hide()



	lalist := widget.NewSelect(ladata, func(value string) {
		//fmt.Println("Select set to", value)
	})
	valist := widget.NewSelect(vadata, func(value string) {
		//fmt.Println("Select set to", value)
	})

	list := widget.NewTable(
        func() (int, int) {
            return len(Ldata), len(Ldata[0])
        },
        func() fyne.CanvasObject {
            mwidget := widget.NewLabel("wide content")
            return mwidget
        },
        func(i widget.TableCellID, o fyne.CanvasObject) {
            o.(*widget.Label).SetText(Ldata[i.Row][i.Col])
            //o.Resize(fyne.NewSize(100, 18))
    })

    list.Hide()
    list.SetColumnWidth(0, 350.0)
    list.SetColumnWidth(1, 350.0)
	buttont := widget.NewButton("加载文件", func() {
			myWindow.Resize(fyne.NewSize(750, 520))
			fd := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
				if err == nil && reader == nil {
					return
				}
				if err != nil {
					dialog.ShowError(err, myWindow)
					return
				}
				//obj_dir(list)
				pathst := strings.Split(reader.URI().String(), "file://")
				Ldata = [][]string{[]string{"账号","密码"}}
				open_file(&Ldata, pathst[1])
				//Ldata = append(Ldata,[]string{"admin","root"})
				//list.Resize(fyne.NewSize(0, 500))
				list.Refresh()
				list.Show()

				//fmt.Println(reader.ReadDir)
			}, myWindow)
			fd.SetFilter(storage.NewExtensionFileFilter([]string{".txt", ".csv"}))
			fd.Show()
			//list.Resize(fyne.NewSize(0, 300))
			fd.Resize(fyne.NewSize(700, 700))

		})


	lalist1 := widget.NewSelect(sadata, func(value string) {
		//fmt.Println("Select set to", value)
		if value == "手动上传"{
			//input.SetPlaceHolder("拖动文件")
			//input1.SetPlaceHolder("")
			lalist.Enable()
			valist.Enable()
			buttont.Show()
			input1.Hide()
		}else{
			//input.SetPlaceHolder("游戏名字")
			lalist.SetSelectedIndex(0)
			valist.SetSelectedIndex(0)
			lalist.Disable()
			valist.Disable()
			input1.Show()
			buttont.Hide()
			list.Hide()
			//input1.SetPlaceHolder("数量")
		}
	})


	button := widget.NewButton("确定", func() {
		text1 := str_curt(input.Text)
		_, err := strconv.Atoi(input1.Text)
		if err != nil && lalist1.SelectedIndex() == 1 || text1 == "" {
			M_dialog("添加提示", "没有游戏名字或数量填写错误", func(mbool bool){}, myWindow)
		}else{
			res := my_data_upload(lalist1.SelectedIndex(), text1, input1.Text, ladata[lalist.SelectedIndex()], vadata[valist.SelectedIndex()], &Ldata)
			call := func(mbool bool) {
				if res == true {
					list.Hide()
				}else{
					list.Show()
				}
				if mbool == true && res == true {
					t_data <- 7
				}
			}
			if res == true{
				Ldata = [][]string{[]string{"账号","密码"}}
				M_dialog("完成提示", "上传完成", call, myWindow)
			}else{
				M_dialog("完成提示", "上传失败", call, myWindow)
			}
		}
		
		
		/*
		messg := dialog.NewConfirm("完成","上传完成",func(mbool bool) {
				list.Hide()
				if mbool == true{
					t_data <- 7
				}
		},myWindow)
		//messg.SetConfirmText("是")
		//messg.SetDismissText("否")
		//messg.Show()
		//fmt.Println(lalist1.SelectedIndex())
		*/
	})

	lalist1.SetSelectedIndex(0)
	lalist.SetSelectedIndex(0)
	valist.SetSelectedIndex(0)
	content := container.New(layout.NewMaxLayout(), list)
	//bos := container.New(layout.NewHBoxLayout())
	box := container.New(layout.NewVBoxLayout(), lalist1,layout.NewSpacer(), input, input1, buttont )
	bos := container.New(layout.NewVBoxLayout(), lalist, valist)
	mbox := container.New(layout.NewGridLayout(1), box, content, bos, button)

	myWindow.SetContent(mbox)
	myWindow.SetCloseIntercept(func(){
		fmt.Println("禁止关闭窗口")
		//myWindow.Hide()
		list.Hide()
		t_data <- 7
	})

	//myWindow.Resize(fyne.NewSize(300, 200))
	//myWindow.CenterOnScreen()
	//myWindow.ShowAndRun()
	return myWindow
}



type Server struct {
    Game 		string `json:"game"`
    Logo   		string `json:"logo"`
    Channel   	string `json:"channel"`
    Model   	string `json:"model"`
    List   		[]string `json:"list"`
}


func my_data_upload(s int, name string, sum string, channe string, model string, Ldata *[][]string) bool {

	switch s {
		case 0:
			var s Server
			s.Game = name
			s.Logo = "0"
			s.Channel = channe
			s.Model = model
			for _, v := range *Ldata {
				if v[0] != "账号" && v[0] != "" {
					s.List = append(s.List, v[0] + "," + v[1])
				}
			}
    		bjson, _ := json.Marshal(s)
    		_, err := post_json(bjson, MconfigIP + "append")
    		if err != nil {
    			return false
    		}
    		return true
		case 1:
			//*Ldata = [][]string{[]string{"账号","密码"}}
			if len(*Ldata) > 1 {
				return my_data_upload(0,name,sum,channe,model, Ldata)
			}
			//fmt.Println(len(*Ldata))
			login_down(sum, Ldata)
			return my_data_upload(0,name,sum,channe,model, Ldata)
	}
	return false

}


func login_down(nums string, Ldata *[][]string) bool {
	var p Data_Headl
	var h Headl

	p.Login.Username = "csb-fan"
	p.Login.Password = "csb512512"
	p.List.PageNo	 = 1
	p.List.PageSize  = 20
	p.Game.GameId	 = 6830
	p.Game.Nums		 = nums
	p.Game.Password	 = "111222"

	bjson, _ := json.Marshal(p.Login)
    
	//fmt.Println(string(bjson))
	ret, err := post_updata(bjson,"https://sdkadmin.youxifan.com/sdkadmin/login/login",h)
	if err != nil {
		fmt.Println("登录错误",err)
		return false
	}
	json.Unmarshal([]byte(ret), &h)
	//fmt.Println("登录返回信息",ret)
	//fmt.Println("token:",h.Token,h.UserId)
	bjson, _ = json.Marshal(p.List)
	//fmt.Println(string(bjson))
	time.Sleep(time.Duration(0)*time.Second)
	ret, err = post_updata(bjson,"https://sdkadmin.youxifan.com/sdkadmin/testdept/page",h)
	if err != nil {
		fmt.Println("获取错误",err)
		return false
	}
	t1 := re_get_time(ret,`"createTime":(\d+?),`)
    //fmt.Println("result1 = ",)
	//fmt.Println("获取返回信息",ret)
	bjson, _ = json.Marshal(p.Game)
	ret, err = post_updata(bjson,"https://sdkadmin.youxifan.com/sdkadmin/testdept/batchreg",h)
	if err != nil {
		fmt.Println("下载失败",err)
		return false
	}
	var url_down string
	var name string
	for {
		time.Sleep(time.Duration(2)*time.Second)
		ret, err = post_updata(bjson,"https://sdkadmin.youxifan.com/sdkadmin/testdept/page",h)
		if err != nil {
			fmt.Println("刷新错误",err)
		}
		urls := re_get_time(ret,`"fileUrl":"(.*?)",`)
		if urls != "" {
			t2 := re_get_time(ret,`"createTime":(\d+?),`)
        	if t1 != t2 {
        		url_down = urls
        		name = t2
        		break
        	}
		}
        fmt.Println("获取中。。。。")
	}
	if get_down(name + ".csv", url_down) == true {
		open_file(Ldata, name + ".csv")
		os.Remove(name + ".csv")
	}
	return true
}	

